﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;

/// <summary>
/// DocOperation 的摘要说明
/// </summary>
public class DocOperation
{

      private Dbcom cm;

    /// <summary>
    /// 体温单信息读取
    /// </summary>
    public Dictionary<string, string> dicRYText = new Dictionary<string, string>();

    public DocOperation(Dbcom Cm)
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
        cm = Cm;
    }

    /// <summary>
    /// 文书拼接
    /// </summary>
    /// <returns></returns>
    public string GetXmlDocs(string textid, string patientid, string Doctype, string NewDocXml)
    {
        try
        {           
            XmlDocument NewDoc = new XmlDocument();
            NewDoc.LoadXml(NewDocXml);

            #region 文书内容查询
            InPatient_Doc[] patient_Docs = null;
            patient_Docs = GetSelectNodes(patientid, textid, Doctype);
            #endregion

            #region 文书内容拼接
            XmlDocument TempXml = new XmlDocument();
            TempXml.PreserveWhitespace = true;
            StringBuilder strBuilder = new StringBuilder();

            string sickarea = "";
            string section = "";
            string bed = "";
            for (int i = 0; i < patient_Docs.Length; i++)
            {
                if (patient_Docs[i] == null)
                    continue;

                XmlDocument ChildXml = new XmlDocument();
                ChildXml.PreserveWhitespace = true;
                ChildXml.LoadXml(patient_Docs[i].Patients_doc);
                if (patient_Docs[i].Isnewpage == "Y")
                {
                    //表示配置中需要进行分页
                    //strBuilder.Append(@"<Skip operatercreater='0' /><p operatercreater='0' />");
                    //文书开头空行
                    strBuilder.Append(@"<Skip operatercreater='0' />");
                }

                sickarea = Dbcom.ReadSqlVal("select sick_area_name from T_PATIENTS_DOC where TID=" + patient_Docs[i].Id + "", 0, "sick_area_name");

                strBuilder.Append(ChildXml.GetElementsByTagName("body")[0].InnerXml);//文书内容
                strBuilder.Append(@"<split textId='" + patient_Docs[i].Id + "' section_name = '" + patient_Docs[i].Section_name +
                    "' bed_no='" + patient_Docs[i].Bed + "' sick_area='" + sickarea + "'/>");


            }

            XmlNode xmlNode = NewDoc.SelectSingleNode("emrtextdoc");//查找<body>
            string ss = strBuilder.ToString();
            foreach (XmlNode bodyNode in xmlNode.ChildNodes)
            {
                if (bodyNode.Name == "body")
                {
                    bodyNode.InnerXml = strBuilder.ToString();
                }
            }
            #endregion
            return NewDoc.OuterXml;
        }
        catch
        {
            return "";
        }


    }


    /// <summary>
    /// 添加已完成文书
    /// </summary>
    public UcTreeNode GetFinishNode(string Id)
    {

        UcTreeNode node = null;
        //if (currentPatient != null)
        //{
            node = SelectDoc(Id);//获得已写文书
        //}
        //取得非住院病程记录文书父节点的ID，拼接字符串以逗号隔开
        string docStr = "";
        if (node != null)
        {
            if (node.Childnodes != null)
            {
                for (int i = 0; i < node.Childnodes.Count; i++)
                {
                    InPatient_Doc doc = node.Childnodes[i].Tag as InPatient_Doc;

                    //docfc = doc;

                    if (doc != null)
                    {
                        if (docStr == "")
                        {
                            docStr = doc.Textkind_id.ToString();
                        }
                        else
                        {
                            docStr += "," + doc.Textkind_id;
                        }
                    }
                }
            }
        }
        UcTreeNode tn_doctor = new UcTreeNode();
        UcTreeNode tn_nurse = new UcTreeNode();       

        tn_doctor.Text = "医生文书";
        tn_nurse.Text = "护士文书";
        //tn_doctor.Image = global::Base_Function.Resource.住院记录;
        //tn_nurse.Image = global::Base_Function.Resource.住院记录;

        //袁杨修改150817
        //if (docStr != "")
        //{
        //    //医生文书
        //    DataInit.getDoctorFinishedText(ref tn_doctor, docStr);                            
        //}

        //医生文书
        getDoctorFinishedText(ref tn_doctor, docStr);

        //护士
        //DataInit.getNurseText(ref tn_nurse);

        //advFinishDoc.Nodes.Add(tn_doctor);
        //advFinishDoc.Nodes.Add(tn_nurse);
       

        foreach (UcTreeNode pNode in node.Childnodes)
        {
            GetPatientDoc(tn_doctor.Childnodes.ToArray(), pNode);
        }

        return tn_doctor;
    }


    /// <summary>
    /// 获取当前文书的一些信息
    /// </summary>
    /// <param name="tid"></param>
    /// <returns></returns>
    public DataSet GetCurrentDocInfo(string tid)
    {
        try
        {          
            string str_sql = "select t.bed_no,t.sick_area_name,t.section_name from  t_patients_doc  t where t.tid =" + tid + "";
            DataSet ds = Dbcom.GetDataSet(str_sql);
            return ds;
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 根据病人住院号，得到该病人的所有文书
    /// </summary>
    /// <param name="patient_id">病人id号</param>
    /// <returns>有文书的树节点</returns>
    public UcTreeNode SelectDoc(string patient_id)
    {
        UcTreeNode nodeTemp = new UcTreeNode();
        nodeTemp.Childnodes = new List<UcTreeNode>();       
        string sql = "select a.tid,a.pid,a.textkind_id,a.belongtosys_id,a.sickkind_id," +
                     " a.textname,a.doc_name,a.patient_Id,a.ishighersign,a.havehighersign,a.havedoctorsign,a.submitted," +
                     "a.createId,a.highersignuserid,a.israplacehightdoctor,a.israplacehightdoctor2,a.SECTION_NAME  from t_patients_doc a " +
                     " where a.patient_Id='" + patient_id + "' order by a.doc_name";
        DataSet ds = Dbcom.GetDataSet(sql);
        if (ds != null)
        {

            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                //去掉重复的文书id
                string tid = "0";
                foreach (DataRow row in dt.Rows)
                {
                    if (row["tid"].ToString() != "")
                    {
                        if (tid != row["tid"].ToString())
                        {
                            InPatient_Doc pDoc = new InPatient_Doc();
                            pDoc.Id = Convert.ToInt32(row["tid"]);
                            pDoc.Patient_id = row["patient_Id"].ToString();
                            pDoc.Pid = row["pid"].ToString();

                            if (row["textkind_id"].ToString() != "")
                                pDoc.Textkind_id = Convert.ToInt32(row["textkind_id"]);

                            if (row["belongtosys_id"].ToString() != "")
                                pDoc.Belongtosys_id = Convert.ToInt32(row["belongtosys_id"]);
                            //pDoc.Patients_doc =row["patients_doc"].ToString();
                            if (row["sickkind_id"].ToString() != "")
                                pDoc.Sickkind_id = Convert.ToInt32(row["sickkind_id"]);

                            pDoc.Docname = row["doc_name"].ToString().TrimStart();
                            pDoc.Textname = row["textname"].ToString().TrimStart();
                            pDoc.Ishighersign = row["ishighersign"].ToString();
                            pDoc.Havehighersign = row["havehighersign"].ToString();
                            pDoc.Havedoctorsign = row["Havedoctorsign"].ToString();
                            pDoc.Submitted = row["submitted"].ToString();
                            pDoc.Createid = row["createId"].ToString();
                            pDoc.Highersignuserid = row["highersignuserid"].ToString();
                            pDoc.Isreplacehighdoctor = row["israplacehightdoctor"].ToString();
                            pDoc.Isreplacehighdoctor2 = row["israplacehightdoctor2"].ToString();
                            pDoc.Section_name = row["SECTION_NAME"].ToString();
                            UcTreeNode node = new UcTreeNode();
                            node.Text = pDoc.Docname;
                            node.Tag = pDoc as object;
                            node.Name = pDoc.Id.ToString();
                            //node.ImageIndex = 19;
                            //node.SelectedImageIndex = 19;
                            nodeTemp.Childnodes.Add(node);
                            tid = row["tid"].ToString();
                        }
                    }
                }
            }
        }
        return nodeTemp;
    }

    /// <summary>
    /// 根据病人住院号，得到该病人当前类型的所有文书
    /// </summary>
    /// <param name="pid">主键</param>
    ///<param name="tid">住文书类型id</param>
    /// <returns>有文书的树节点</returns>
    public UcTreeNode SelectDoc(int id, string tid)
    {        
        UcTreeNode nodeTemp = new UcTreeNode();
        string sql = "select tid,pid,textkind_id,belongtosys_id,sickkind_id,textname,doc_name,patient_Id " +
                     "from t_patients_doc where patient_Id='" + id + "' and textkind_id=" +
                      tid + " order by sickkind_id desc";
        DataSet ds = Dbcom.GetDataSet(sql);
        if (ds != null)
        {
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    InPatient_Doc pDoc = new InPatient_Doc();
                    pDoc.Id = Convert.ToInt32(row["tid"]);
                    pDoc.Pid = row["pid"].ToString();
                    pDoc.Patient_id = row["patient_Id"].ToString();
                    if (row["textkind_id"].ToString() != "")
                        pDoc.Textkind_id = Convert.ToInt32(row["textkind_id"]);
                    if (row["belongtosys_id"].ToString() != "")
                        pDoc.Belongtosys_id = Convert.ToInt32(row["belongtosys_id"]);
                    //pDoc.Patients_doc =row["patients_doc"].ToString();
                    if (row["sickkind_id"].ToString() != "")
                        pDoc.Sickkind_id = Convert.ToInt32(row["sickkind_id"]);

                    pDoc.Docname = row["doc_name"].ToString().TrimStart();
                    pDoc.Textname = row["textname"].ToString().TrimStart();

                    UcTreeNode node = new UcTreeNode();
                    node.Text = pDoc.Docname;
                    node.Tag = pDoc as object;
                    node.Name = pDoc.Id.ToString();
                    //node.ImageIndex = 22;
                    nodeTemp.Childnodes.Add(node);
                }

            }
        }
        return nodeTemp;
    }


    /// <summary>
    /// 获得当前节点下面所有病人文书的节点
    /// </summary>
    /// <param name="nodes">当前节点下的所有文书内容</param>
    /// <returns>返回Patient_Doc集合</returns>
    public InPatient_Doc[] GetSelectNodes(string textid, string patient_id)
    {       
        InPatient_Doc[] patient_Docs = null;
        if (patient_id != null)
        {

            string sql = "select a.tid,a.textname,a.textkind_id,a.doc_name,c.issimpleinstance,a.section_name,c.ISNEWPAGE,Bed_no from t_patients_doc a" +
                         " inner join t_text c on a.textkind_id = c.id" +
                         " where patient_id='" + patient_id + "'  and  textkind_id!=134" +    //textkind_id=134术前讨论
                         " and parentid=" + textid + "  and submitted='Y' order by doc_name";
            DataSet ds = Dbcom.GetDataSet(sql);
            if (ds != null)
            {
                DataTable dt = ds.Tables[0];
                if (dt != null)
                {
                    //arrs = new string[dt.Rows.Count,2];
                    //去掉相同的文书
                    int tid = 0;
                    patient_Docs = new InPatient_Doc[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {

                        if (tid != Convert.ToInt32(dt.Rows[i]["tid"].ToString()))
                        {

                            patient_Docs[i] = new InPatient_Doc();
                            patient_Docs[i].Patients_doc = Dbcom.ReadSqlVal("select * from T_PATIENT_DOC_COLB where tid=" + dt.Rows[i]["tid"].ToString() + "", 0, "CONTENT");
                            //if (patient_Docs[i].Patients_doc == "" || patient_Docs[i].Patients_doc == null)
                            //{
                            //    patient_Docs[i].Patients_doc = Dbcom.DownLoadFtpPatientDoc(dt.Rows[i]["tid"].ToString() + ".xml", currentPatient.Id.ToString());

                            //}
                            patient_Docs[i].Id = Convert.ToInt32(dt.Rows[i]["tid"].ToString());
                            patient_Docs[i].Textkind_id = Convert.ToInt32(dt.Rows[i]["textkind_id"].ToString());
                            patient_Docs[i].Belongtosys_id = Convert.ToInt32(dt.Rows[i]["issimpleinstance"].ToString());
                            patient_Docs[i].Docname = dt.Rows[i]["doc_name"].ToString();
                            patient_Docs[i].Section_name = dt.Rows[i]["section_name"].ToString();
                            patient_Docs[i].Bed = dt.Rows[i]["Bed_no"].ToString();
                            tid = Convert.ToInt32(dt.Rows[i]["tid"].ToString());

                            if (dt.Rows[i]["ISNEWPAGE"].ToString() == "Y")
                            {
                                patient_Docs[i].Isnewpage = "Y";
                            }
                            else
                            {
                                patient_Docs[i].Isnewpage = "N";
                            }
                        }
                    }
                }
            }
        }
        return patient_Docs;

    }



    /// <summary>
    /// 过滤基本信息
    /// </summary>
    /// <param name="bodyElement">xml内容</param>
    /// <param name="InpatientInfo">病人基本信息实体</param>
    /// <param name="TextKind_id">文书类型</param>
    /// <param name="Tid">所写的文书ID</param>
    public  void filterInfo(XmlElement bodyElement, InPatientInfo InpatientInfo, int TextKind_id, int Tid)
    {       
        string strDwdz = "";
        string strSql = "select t.office_address from t_in_patient t where t.id='" + InpatientInfo.Id + "'";
        DataSet ds_dwdz = Dbcom.GetDataSet(strSql);
        if (ds_dwdz.Tables[0].Rows.Count > 0)
        {
            strDwdz = ds_dwdz.Tables[0].Rows[0]["office_address"].ToString();
        }
        if (dicRYText.Count == 0)
        {
            //重新获取入院记录中相关值
            dicRYText = GetTextInfo(InpatientInfo, TextKind_id.ToString());
        }
        XmlNodeList list;
        if (bodyElement.GetElementsByTagName("body").Count > 0)
        {
            XmlNode body = bodyElement.GetElementsByTagName("body")[0];

            list = body.ChildNodes;


            setXmlFont(list, bodyElement);
            if (list != null)
            {
                if (list.Count > 0 && InpatientInfo != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i].Attributes["title"] != null && list[i].Name == "div")
                        {
                            if (InpatientInfo.Gender_Code == "0" || InpatientInfo.Gender_Code == "男")
                            {
                                if (list[i].Attributes["title"].Value.ToString().Contains("月经婚育史") ||
                                    list[i].Attributes["title"].Value.ToString().Contains("月经史"))
                                {

                                    body.RemoveChild(list[i]);
                                }
                            }
                            //else
                            //{
                            //    if (InpatientInfo.Age < 14)
                            //    {
                            //        body.RemoveChild(list[i]);
                            //    }
                            //}
                        }
                    }
                }
            }
        }

        //if (App.UserAccount.CurrentSelectRole.Section_Id == InpatientInfo.Section_Id.ToString())
        //{
        //    list = bodyElement.GetElementsByTagName("head");
        //    if (list != null)
        //    {
        //        if (list.Count > 0)
        //            bodyElement.RemoveChild(list[0]);
        //    }
        //}

        string str = "0";
        //XmlNodeList list = bodyElement.GetElementsByTagName("input");                        
        list = bodyElement.GetElementsByTagName("input");
        if (list != null)
        {
            if (list.Count > 0 && InpatientInfo != null)
            {


                for (int i = 0; i < list.Count; i++)
                {

                    //袁杨添加160601  护士站签名功能全部使用电子签名
                    foreach (XmlElement spanEle in list)
                    {
                        XmlAttribute nameAtt = spanEle.Attributes["name"];
                        if (nameAtt != null && nameAtt.Value.ToString() == "护士签名")
                        {
                            spanEle.SetAttribute("candelete", "1");
                        }
                    }


                    if (list[i].Attributes["name"] != null)
                    {
                        if (list[i].InnerText.Trim() == "" || Tid == 0)
                        {
                            //string sss = list[i].Attributes["name"].Value.ToString().Trim();
                            //if (sss.Contains("体温") || sss.Contains("脉搏") || sss.Contains("呼吸"))
                            //{
                            //    sss = "aaaa" + sss;
                            //}



                            switch (list[i].Attributes["name"].Value.ToString().Trim())
                            {
                                case "家庭地址":
                                case "us_jtdz":
                                    list[i].InnerText = InpatientInfo.Home_address;
                                    break;
                                case "现住址":
                                    list[i].InnerText = InpatientInfo.Now_address.Replace("|", "");
                                    break;
                                //case "联系电话":
                                //    list[i].InnerText = InpatientInfo.Relation_phone;//Home_phone
                                //    break;
                                case "家庭电话":
                                    list[i].InnerText = InpatientInfo.Now_addres_phone;
                                    break;
                                case "联系人":
                                    list[i].InnerText = InpatientInfo.Relation_name;
                                    break;
                                case "户口邮编":
                                    list[i].InnerText = InpatientInfo.HomePostal_code;
                                    break;
                                case "姓名":
                                case "us_xm":
                                    list[i].InnerText = InpatientInfo.Patient_Name;
                                    break;

                                case "出生日期":

                                    list[i].InnerText = Convert.ToDateTime(InpatientInfo.Birthday).ToString("yyyy-MM-dd");
                                    break;

                                case "出生地":
                                case "us_csd":
                                    if (InpatientInfo.Birth_place != null) //home_address
                                        list[i].InnerText = InpatientInfo.Birth_place.Replace("|", "");
                                    break;
                                case "户口地址":
                                    list[i].InnerText = InpatientInfo.Home_address;
                                    break;
                                case "性别":
                                case "us_xb":
                                    if (InpatientInfo.Gender_Code == "0" || InpatientInfo.Gender_Code == "男")
                                        list[i].InnerText = "男";
                                    else
                                        list[i].InnerText = "女";
                                    break;
                                case "民族":
                                case "us_mz":
                                    list[i].InnerText = InpatientInfo.Folk_code;
                                    break;
                                case "年龄":
                                case "us_nl":
                                    if (InpatientInfo.Age != null && InpatientInfo.Age != "" && InpatientInfo.Age != "0" && InpatientInfo.Age != "-")
                                    {
                                        if (InpatientInfo.Age.Contains("岁"))
                                            list[i].InnerText = InpatientInfo.Age.ToString();
                                        else
                                            list[i].InnerText = InpatientInfo.Age.ToString() + "岁";
                                    }
                                    else
                                        if (InpatientInfo.Child_age != null)
                                        list[i].InnerText = InpatientInfo.Child_age.ToString();
                                    break;
                                case "入院时间":
                                case "us_rysj":
                                case "入院日期":
                                case "us_ryrq":
                                    //if (TextKind_id == 158)
                                    //    list[i].InnerText = InpatientInfo.In_Time.ToString("yyyy-MM-dd");
                                    //else
                                    list[i].InnerText = InpatientInfo.In_Time.ToString("yyyy-MM-dd，HH:mm");
                                    break;
                                case "出院时间":
                                    list[i].InnerText = InpatientInfo.Die_time.ToString("yyyy-MM-dd，HH:mm");
                                    break;
                                case "记录日期":
                                case "us_jlrq":
                                    if (TextKind_id == 158)
                                        list[i].InnerText = Dbcom.GetSystemTime().ToString("yyyy-MM-dd");
                                    else
                                        list[i].InnerText = Dbcom.GetSystemTime().ToString("yyyy-MM-dd，HH:mm");
                                    break;
                                case "婚姻":
                                case "us_hy":
                                    //袁杨修改 151023
                                    //string str_hy = "select name from t_data_code t where t.type='132' and t.code='" + InpatientInfo.Marrige_State + "'";
                                    //DataSet dst_hy = App.GetDataSet(str_hy);
                                    //if (dst_hy.Tables[0].Rows.Count > 0)
                                    //{
                                    //    list[i].InnerText = dst_hy.Tables[0].Rows[0]["name"].ToString();
                                    //}
                                    //else
                                    //{
                                    //    list[i].InnerText = "";
                                    //}

                                    list[i].InnerText = InpatientInfo.Marrige_State.ToString();
                                    break;
                                case "职业":
                                case "us_zy":
                                    if (InpatientInfo.Career != null && !InpatientInfo.Career.Contains("其他"))
                                        list[i].InnerText = InpatientInfo.Career;
                                    else
                                        list[i].InnerText = InpatientInfo.Career_other;
                                    break;
                                case "单位及职业":
                                case "us_dwjzy":
                                    if (InpatientInfo.Career != null && !InpatientInfo.Career.Contains("其他"))
                                        list[i].InnerText = InpatientInfo.Office + "  " + InpatientInfo.Career;
                                    else
                                        list[i].InnerText = InpatientInfo.Office + "  " + InpatientInfo.Career_other;
                                    break;
                                case "工作单位":
                                case "us_gzdw":
                                    list[i].InnerText = InpatientInfo.Office;
                                    break;
                                case "单位":
                                    list[i].InnerText = strDwdz;
                                    break;
                                case "住址":
                                case "us_jtzz":
                                    list[i].InnerText = InpatientInfo.Home_address;
                                    break;
                                case "us_jg":
                                case "籍贯":
                                    if (InpatientInfo.Natiye_place != null)
                                        list[i].InnerText = InpatientInfo.Natiye_place.Replace("|", "");
                                    break;
                                //注释掉 袁杨 150825
                                //case "初步诊断":
                                //    list[i].InnerText = "";
                                //    break;
                                case "住院号":
                                case "us_zyh":
                                    list[i].InnerText = InpatientInfo.PId;
                                    break;
                                case "住院日数":
                                    TimeSpan timespan = Convert.ToDateTime(Dbcom.GetSystemTime().ToString("yyyy-MM-dd")) - Convert.ToDateTime(InpatientInfo.In_Time.ToString("yyyy-MM-dd"));
                                    if (timespan.Days == 0 || timespan.Days == 1)
                                    {
                                        list[i].InnerText = "1";
                                    }
                                    else if (timespan.Days > 1)
                                    {
                                        list[i].InnerText = timespan.Days.ToString();
                                    }
                                    break;
                                case "科室":
                                case "us_ks":
                                    //case "请求会诊科":
                                    list[i].InnerText = InpatientInfo.Section_Name;
                                    break;
                                case "病区":
                                case "us_bq":
                                    list[i].InnerText = InpatientInfo.Sick_Area_Name;
                                    break;
                                case "床号":
                                case "us_ch":
                                    list[i].InnerText = InpatientInfo.Sick_Bed_Name;
                                    break;
                                case "身份证":
                                case "us_sfz":
                                    //if (InpatientInfo.Card_Id.Length > 10)
                                    //{
                                    //    list[i].InnerText = InpatientInfo.Card_Id;
                                    //}
                                    //袁杨修改 151111
                                    if (InpatientInfo.Medicare_no.Length > 10)
                                    {
                                        list[i].InnerText = InpatientInfo.Medicare_no;
                                    }

                                    break;
                                case "his_id":
                                    //if (!string.IsNullOrEmpty(Us.InpatientInfo.His_id))
                                    //{
                                    list[i].InnerText = InpatientInfo.His_id;
                                    //}
                                    break;
                                case "病案号":
                                    list[i].InnerText = InpatientInfo.PId;
                                    break;
                                //体温T,P,R,BP
                                case "体重":
                                case "体温":
                                case "脉搏":
                                case "呼吸":
                                case "收缩压":
                                case "舒张压":
                                    if (dicRYText.Count > 0 && dicRYText.ContainsKey(list[i].Attributes["name"].Value.ToString().Trim()))
                                        if (list[i].Attributes["name"].Value.ToString().Trim() != "收缩压")
                                        {
                                            list[i].InnerText = dicRYText[list[i].Attributes["name"].Value.ToString().Trim()].ToString();
                                        }

                                        else
                                        {
                                            //袁杨修改 空值不进行处置 151106
                                            if (dicRYText[list[i].Attributes["name"].Value.ToString().Trim()].ToString() != "")
                                            {
                                                //list[i].InnerText = dicRYText[list[i].Attributes["name"].Value.ToString().Trim()].ToString().Substring(1);
                                                list[i].InnerText = dicRYText[list[i].Attributes["name"].Value.ToString().Trim()].ToString();
                                            }
                                            else
                                            {
                                                list[i].InnerText = dicRYText[list[i].Attributes["name"].Value.ToString().Trim()].ToString();

                                            }
                                        }
                                    break;

                                case "住院次数":
                                    list[i].InnerText = InpatientInfo.InHospital_count.ToString();
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 过滤签名
    /// </summary>
    /// <param name="bodyElement"></param>
    /// <param name="TextKind_id"></param>
    public void filterInfo(XmlElement bodyElement, int TextKind_id)
    {
        //1963,125,126,127,130,131,132,135,136,153,301,890,891,741

        //过滤病程记录下的所有类型的文书 武汉这边很多住院治要过滤TextKind_id从119-47560141
        if (TextKind_id == 1963 ||
            TextKind_id == 125 ||
            TextKind_id == 126 ||
            TextKind_id == 127 ||
            TextKind_id == 130 ||
            TextKind_id == 131 ||
            TextKind_id == 132 ||
            TextKind_id == 135 ||
            TextKind_id == 136 ||
            TextKind_id == 153 ||
            TextKind_id == 301 ||
            TextKind_id == 890 ||
            TextKind_id == 891 ||
            TextKind_id == 741 ||
            TextKind_id == 119 ||
            TextKind_id == 47553087 || TextKind_id == 47553088 ||
            TextKind_id == 47553089 || TextKind_id == 47561196 ||
            TextKind_id == 63471477 || TextKind_id == 47607562 ||
            TextKind_id == 47587230 || TextKind_id == 47560141)
        {
            XmlNodeList list;
            list = bodyElement.GetElementsByTagName("input");
            XmlNode body = bodyElement.GetElementsByTagName("body")[0];
            if (list != null)
            {
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i].Attributes["name"] != null)
                        {
                            if (list[i].Attributes["name"].Value.ToString().Contains("医师签名") ||
                                //袁杨添加 150108
                                list[i].Attributes["name"].Value.ToString().Contains("联系人关系") ||
                                list[i].Attributes["name"].Value.ToString().Contains("国籍") ||
                                list[i].Attributes["name"].Value.ToString().Contains("联系人地址") ||
                                list[i].Attributes["name"].Value.ToString().Contains("联系人") ||
                                list[i].Attributes["name"].Value.ToString().Contains("出生地") ||
                                list[i].Attributes["name"].Value.ToString().Contains("户口地址") ||
                                list[i].Attributes["name"].Value.ToString().Contains("联系人电话") ||
                                list[i].Attributes["name"].Value.ToString().Contains("体温") ||
                                list[i].Attributes["name"].Value.ToString().Contains("收缩压") ||
                                list[i].Attributes["name"].Value.ToString().Contains("舒张压") ||
                                list[i].Attributes["name"].Value.ToString().Contains("脉搏") ||
                                list[i].Attributes["name"].Value.ToString().Contains("呼吸") ||
                                list[i].Attributes["name"].Value.ToString().Contains("日期") ||
                                list[i].Attributes["name"].Value.ToString().Contains("出生日期") ||
                                //
                                list[i].Attributes["name"].Value.ToString().Contains("时间"))
                            {
                                try
                                {
                                    list[i].InnerText = "";
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //<summary>
    //获取相关的文书信息
    //</summary>
    //<param name="inPatient">住院病人</param>
    //<returns></returns>
    public Dictionary<string, string> GetTextInfo(InPatientInfo inPatient, string textId)
    {       
        Dictionary<string, string> dic = new Dictionary<string, string>();
        string textlist = "47560141,119,47553087,47553088,47553089,47561196,102,120,121,125,6976553,1309865603,123992553";
        if (textlist.Contains(textId))//入院记录类型id
        {//打开入院记录时,需获取T,P,R,BP值
            try
            {
                //体温单首次T,P,R,BP
                if ((inPatient.Section_Name.Contains("ICU") || inPatient.Section_Name.Contains("神经")) && (inPatient.Sick_Area_Name.Contains("ICU") || inPatient.Sick_Area_Name.Contains("神经")))
                {
                    string TPRBPSql = "select * from (select measure_time,TEMPERATURE_VALUE,PULSE_VALUE,BREATH_VALUE, " +
                                    "(select bp_blood from (select tt.record_time,tt.bp_blood from t_temperature_info tt  " +
                                    "where patient_id='" + inPatient.Id + "' and bp_blood is not null order by record_time ) where rownum=1) bp_blood " +
                                    " from t_vital_signs  where patient_id='" + inPatient.Id + "' and TEMPERATURE_VALUE<>0.0 order by measure_time) where rownum=1";
                    DataTable dtTPRBP = Dbcom.GetDataSet(TPRBPSql).Tables[0];
                    if (dtTPRBP.Rows.Count > 0)
                    {
                        dic.Add("体温", Convert.ToDouble(dtTPRBP.Rows[0]["TEMPERATURE_VALUE"]).ToString());
                        string PULSE_VALUE = dtTPRBP.Rows[0]["PULSE_VALUE"].ToString();
                        if (PULSE_VALUE == "0" || PULSE_VALUE == "0.0")
                        { }
                        else
                        {
                            dic.Add("脉搏", PULSE_VALUE);
                        }
                        string BREATH_VALUE = dtTPRBP.Rows[0]["BREATH_VALUE"].ToString();
                        if (BREATH_VALUE == "0" || BREATH_VALUE == "0.0")
                        { }
                        else
                        {
                            dic.Add("呼吸", dtTPRBP.Rows[0]["BREATH_VALUE"].ToString());
                        }

                        string bp_blood = dtTPRBP.Rows[0]["bp_blood"].ToString().Trim();//O128/84,T140/80
                        if (!string.IsNullOrEmpty(bp_blood))
                        {
                            if (bp_blood.Contains("/"))
                            {
                                if (bp_blood.Contains(","))
                                {
                                    string[] bloods = bp_blood.Split(',');
                                    if (bloods[0].Contains("/"))
                                        bp_blood = bloods[0];
                                    else
                                        bp_blood = bloods[1];
                                }
                                string[] us_blood = bp_blood.Split('/');
                                dic.Add("收缩压", us_blood[0]);
                                dic.Add("舒张压", us_blood[1]);
                            }
                        }

                        //if (bp_blood != "")
                        //{
                        //if (!bp_blood.ToString().Contains(","))
                        //{
                        //    if(bp_blood)
                        //    string[] one = bp_blood.Split('/');//bp_blood.Substring(1, bp_blood.Length - 1).Split('/')
                        //    if (one.Length > 1)
                        //    {
                        //        dic.Add("收缩压", one[0]);
                        //        dic.Add("舒张压", one[1]);
                        //    }
                        //}
                        //else
                        //{
                        //    string[] bloodArr = bp_blood.Split(',');
                        //    if (bloodArr.Length > 0)
                        //    {
                        //        string[] bloodOne = bloodArr[0].Substring(1, bloodArr[0].Length - 1).Split('/');
                        //        if (bloodOne.Length > 1)
                        //        {
                        //            dic.Add("收缩压", bloodOne[0]);
                        //            dic.Add("舒张压", bloodOne[1]);
                        //        }
                        //    }
                        //}
                        //}
                    }
                }
                else//精神科入院记录的获取生命体征方式不一样，单独写方法
                {
                    string str_jsk_sql = "select bed_no, pid, measure_time, t_val, valtype, patient_id from t_vital_signs_jsk where patient_id='" + inPatient.Id + "' order  by measure_time desc";
                    DataSet ds_jsk_sql = Dbcom.GetDataSet(str_jsk_sql);
                    if (ds_jsk_sql.Tables[0].Rows.Count > 0)
                    {
                        string strMark_tw = "";
                        string strMark_mb = "";
                        string strMark_hx = "";
                        string strMark_xy = "";
                        string strMark_sg = "";
                        string strMark_tz = "";
                        for (int i = 0; i < ds_jsk_sql.Tables[0].Rows.Count; i++)
                        {
                            if (ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString() != "" && ds_jsk_sql.Tables[0].Rows[i]["valtype"].ToString() == "腋温")
                            {

                                if (strMark_tw == "")
                                {
                                    dic.Add("体温", Convert.ToDouble(ds_jsk_sql.Tables[0].Rows[i]["t_val"]).ToString());
                                    strMark_tw = ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString();
                                }

                            }
                            if (ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString() != "" && ds_jsk_sql.Tables[0].Rows[i]["valtype"].ToString() == "脉搏")
                            {

                                if (strMark_mb == "")
                                {
                                    dic.Add("脉搏", Convert.ToDouble(ds_jsk_sql.Tables[0].Rows[i]["t_val"]).ToString());
                                    strMark_mb = ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString();
                                }

                            }
                            if (ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString() != "" && ds_jsk_sql.Tables[0].Rows[i]["valtype"].ToString() == "呼吸")
                            {

                                if (strMark_hx == "")
                                {
                                    dic.Add("呼吸", Convert.ToDouble(ds_jsk_sql.Tables[0].Rows[i]["t_val"]).ToString());
                                    strMark_hx = ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString();
                                }

                            }
                            if (ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString() != "" && ds_jsk_sql.Tables[0].Rows[i]["valtype"].ToString() == "血压1")
                            {

                                if (strMark_xy == "")
                                {
                                    string bp_blood = ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString().Trim();//O128/84,T140/80
                                    if (!string.IsNullOrEmpty(bp_blood))
                                    {
                                        if (bp_blood.Contains("/"))
                                        {
                                            if (bp_blood.Contains(","))
                                            {
                                                string[] bloods = bp_blood.Split(',');
                                                if (bloods[0].Contains("/"))
                                                    bp_blood = bloods[0];
                                                else
                                                    bp_blood = bloods[1];
                                            }
                                            string[] us_blood = bp_blood.Split('/');
                                            dic.Add("收缩压", us_blood[0]);
                                            dic.Add("舒张压", us_blood[1]);
                                        }

                                    }
                                    strMark_xy = bp_blood;
                                }

                            }
                            if (textId == "1309865603")//1309865603--精神科入院护理评估记录单
                            {
                                //if (ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString() != "" && ds_jsk_sql.Tables[0].Rows[i]["valtype"].ToString() == "身高")
                                //{

                                //    if (strMark_sg == "")
                                //    {
                                //        dic.Add("身高", Convert.ToDouble(ds_jsk_sql.Tables[0].Rows[i]["t_val"]).ToString());
                                //        strMark_sg = ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString();
                                //    }

                                //}
                                if (ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString() != "" && ds_jsk_sql.Tables[0].Rows[i]["valtype"].ToString() == "体重")
                                {

                                    if (strMark_tz == "")
                                    {
                                        dic.Add("体重", Convert.ToDouble(ds_jsk_sql.Tables[0].Rows[i]["t_val"]).ToString());
                                        strMark_tz = ds_jsk_sql.Tables[0].Rows[i]["t_val"].ToString();
                                    }

                                }
                            }

                        }
                    }
                }
                return dic;
            }
            catch (System.Exception ex)
            { return dic; }
        }
        return dic;
    }

   

    public void setXmlHead(XmlElement bodyElement, string sickarea_name, string bed_no, string section)
    {
        try
        {
            XmlNode head = bodyElement.GetElementsByTagName("head")[0];
            head.Attributes["sick_area"].Value = sickarea_name;
            head.Attributes["section_name"].Value = sickarea_name;
            head.Attributes["bed_name"].Value = section;
        }
        catch (System.Exception ex)
        {
        }
    }

    /// <summary>
    /// 将住院日志里面的部分内容和首程同步
    /// </summary>
    /// <param name="text_id"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    public string DocFromXmlBytText(string text_id,string patient_id)
    {
        string content = "";
        try
        {          

            /*
             * 获取默认模版             
             */
            TemplateOperation tp = new TemplateOperation(cm);
             content=tp.GetDefaultTemp(text_id);

            if (!Text_id_haveDoc(text_id, patient_id))
            {
                return content;
            }
            if (string.IsNullOrEmpty(content))
                return content;
            else
            {
                //源内容
                string text_tid = getTidByTextid(text_id,patient_id);

                XmlDocument tmpxml_source = new XmlDocument();
                tmpxml_source.PreserveWhitespace = true;
                string content_source = "";
                content_source = Dbcom.ReadSqlVal("select * from T_PATIENT_DOC_COLB where tid=" + text_tid + "", 0, "CONTENT");
                //if (content_source == "" || content_source == null)
                //{
                //    content_source = App.DownLoadFtpPatientDoc(text_tid + ".xml", patient_id);
                //}
                tmpxml_source.LoadXml(content_source);

                //当前内容  读取内容： 主诉 现病史 既往史
                XmlDocument tempxmldoc = new XmlDocument();
                tempxmldoc.PreserveWhitespace = true;
                if (content.Contains("emrtextdoc"))
                {
                    tempxmldoc.LoadXml(content);
                    XmlNode xmlNode = tempxmldoc.SelectSingleNode("emrtextdoc");//查找<body>
                    XmlNode bodynode = tempxmldoc.ChildNodes[0].SelectSingleNode("body");
                    XmlNodeList list = ((XmlElement)bodynode).GetElementsByTagName("div");
                    foreach (XmlNode xn in list)
                    {
                        if (xn.Attributes["title"] != null)
                        {
                            string xnname = xn.Attributes["title"].Value.ToString().Trim();
                            if (!string.IsNullOrEmpty(xnname) && isCloneContent(xnname, text_id))
                            {
                                if (text_id == "125")
                                {
                                    if (!string.IsNullOrEmpty(xmlContent(tmpxml_source, xnname)))
                                    {
                                        xn.InnerXml = xmlContent(tmpxml_source, xnname);//InnerText
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(docContent(tmpxml_source, xnname)))
                                    {
                                        xn.InnerXml = docContent(tmpxml_source, xnname);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    tempxmldoc.LoadXml("<emrtextdoc/>");
                    XmlNode xmlNode = tempxmldoc.SelectSingleNode("emrtextdoc");//查找<body>
                    XmlNode bodynode = tempxmldoc.ChildNodes[0].SelectSingleNode("body");
                    XmlNodeList list = ((XmlElement)bodynode).GetElementsByTagName("div");
                    foreach (XmlNode xn in list)
                    {
                        if (xn.Attributes["title"] != null)
                        {
                            string xnname = xn.Attributes["title"].Value.ToString().Trim();
                            if (!string.IsNullOrEmpty(xnname) && isCloneContent(xnname, text_id))
                            {
                                if (text_id == "125")
                                {
                                    //InnerXml读取结构  InnerText读取内容
                                    if (!string.IsNullOrEmpty(xmlContent(tmpxml_source, xnname)))
                                    {
                                        xn.InnerXml = xmlContent(tmpxml_source, xnname);
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(docContent(tmpxml_source, xnname)))
                                    {
                                        xn.InnerXml = docContent(tmpxml_source, xnname);
                                    }
                                }
                            }
                        }
                    }
                }
                content = tempxmldoc.InnerXml;
            }

            return content;
        }
        catch
        {
            return content;
        }
    }




    /// <summary>
    /// 文书删除
    /// </summary>
    /// <param name="nodeid"></param>
    /// <param name="DocType"></param>
    /// <param name="doc"></param>
    /// <returns>1-封存 2-会诊记录 3-不是管床医生</returns>
    public int DeleteDocById(string nodeid,string DocType,InPatientInfo inpt,string User_id,string User_name)
    {
        string result = null;
        string log_Tid = "";
        log_Tid = nodeid;
        int count = 0;
        InPatient_Doc doc=GetDocbyId(nodeid, inpt.Id.ToString(), DocType);
       
        if (DocType.Contains("Patient_Doc"))
        {           
            string book_Id = nodeid;
            //文书删除权限，有上级医师签字，管床不能删，有管床医师签字，实习生研究生不能删           
            bool isDelete = false;         
            string strSql_fc = "select t.issafeup from t_patients_doc t where t.tid='" + doc.Id + "'";
            DataSet ds_fc = Dbcom.GetDataSet(strSql_fc);
            if (ds_fc.Tables[0].Rows.Count > 0)
            {
                if (ds_fc.Tables[0].Rows[0]["issafeup"].ToString() == "0")
                {                  
                    return 1;
                }
            }

            //袁杨添加170328
            if (doc.Textkind_id == 133)
            {                
                return 2;
            }
            if (doc.Submitted == "Y")
            {
                #region 已提交文书的删除
                isDelete = ISDelByXmlNode(doc.Id, inpt.Id.ToString(), User_name);
                if (isDelete)
                {
                    if (inpt.Sick_Doctor_Id == User_id ||
                       User_id == doc.Createid)
                    {
                        InPatient_Doc pdoc = doc;
                        //patient_doc
                        string sql_Patient = "delete t_patients_doc where tid = " + pdoc.Id + "";
                        //quelsty
                        string sql_Quality = "delete t_quality_text where tid = " + pdoc.Id + "";
                        //t_trend_diagnose
                        string sql_trend = "delete t_trend_diagnose where diagnoseitem_id in(select id from t_diagnose_item where doc_id = " + pdoc.Id + ")";
                        //t_diagnose_item
                        string sql_item = "delete t_diagnose_item where doc_id = " + pdoc.Id;
                        //插入到文书历史表
                        string sql_InsertDocHistory = "insert into t_patients_doc_delhistory(tid,pid,textkind_id,belongtosys_id,sickkind_id,textname,childid,deltime,delopeaterid,createid,patient_id,doc_name)" +
                                                      " select tid,pid,textkind_id,belongtosys_id,sickkind_id,textname,childid,sysdate," + User_id + ",createid,patient_id,doc_name from  t_patients_doc where tid=" + pdoc.Id + "";                        
                        string[] arr = new string[5];
                        arr[0] = sql_InsertDocHistory;
                        arr[1] = sql_Patient;
                        arr[2] = sql_Quality;
                        arr[3] = sql_trend;
                        arr[4] = sql_item;                      

                        count = 0;
                        try
                        {
                            count = Dbcom.ExecuteBatch(arr);
                        }
                        catch (Exception)
                        {

                            result = "F";
                        }
                    }
                    else
                    {
                        return 3;
                    }
                }
                #endregion
            }
            else
            {
                #region 暂存删除
                //patient_doc
                string sql_Patient = "delete t_patients_doc where tid = " + doc.Id + "";
                //quelsty
                string sql_Quality = "delete t_quality_text where tid = " + doc.Id + "";
                //t_trend_diagnose
                string sql_trend = "delete t_trend_diagnose where diagnoseitem_id in(select id from t_diagnose_item where doc_id = " + doc.Id + ")";
                //t_diagnose_item
                string sql_item = "delete t_diagnose_item where doc_id = " + doc.Id;

                ///
                string sql_Patient_clob = "delete t_patient_doc_colb where tid = " + doc.Id + "";

                string[] arr = new string[5];
                arr[0] = sql_Patient;
                arr[1] = sql_Quality;
                arr[2] = sql_trend;
                arr[3] = sql_item;
                arr[4] = sql_Patient_clob;

                count = 0;
                try
                {
                    count = Dbcom.ExecuteBatch(arr);
                }
                catch (Exception)
                {

                    result = "F";
                }
                #endregion
            }
                               
                       
        }
        else if (DocType.Contains("Class_Text"))//单例文书删除
        {                         

                string strSql_fc1 = "select t.issafeup from t_patients_doc t where t.textkind_id='" + nodeid + "'";
                DataSet ds_fc1 = Dbcom.GetDataSet(strSql_fc1);
                if (ds_fc1.Tables[0].Rows.Count > 0)
                {
                    if (ds_fc1.Tables[0].Rows[0]["issafeup"].ToString() == "0")
                    {                       
                        return 1;
                    }
                }

                //string User_id = UserAccount.UserInfo.User_id;
                string book_Id = nodeid;

                //文书删除权限，有上级医师签字，管床不能删，有管床医师签字，实习生研究生不能删

                //if (App.UserAccount.UserInfo.User_id != doc.Createid && doc.Textkind_id != 2172 && doc.Textkind_id != 2173)
                ////'电脑血糖监测记录单','PICC护理记录单')
                //{//删除权限判断当前用户是否是创建人
                //    return;
                //}
                bool isDelete = ISDelByXmlNode(doc.Id, inpt.Id.ToString(),User_name);
            if (isDelete)
            {

                //patient_doc
                string sql_Patient = "delete t_patients_doc where tid = " + doc.Id + "";
                //quelsty
                string sql_Quality = "delete t_quality_text where tid = " + doc.Id + "";
                //插入到文书历史表
                string sql_InsertDocHistory = "insert into t_patients_doc_delhistory(tid,pid,textkind_id,belongtosys_id,sickkind_id,textname,childid,deltime,delopeaterid,createid,patient_id)" +
                                              " select tid,pid,textkind_id,belongtosys_id,sickkind_id,textname,childid,sysdate," + User_id + ",createid,patient_id from  t_patients_doc where tid=" + doc.Id + "";
                //t_trend_diagnose
                string sql_trend = "delete t_trend_diagnose where diagnoseitem_id in(select id from t_diagnose_item where doc_id = " + doc.Id + ")";
                //t_diagnose_item
                string sql_item = "delete t_diagnose_item where doc_id = " + doc.Id;

                string sql_Patient_clob = "delete t_patient_doc_colb where tid = " + doc.Id + "";

                string[] arr = new string[6];
                arr[0] = sql_InsertDocHistory;
                arr[1] = sql_Patient;
                arr[2] = sql_Quality;
                arr[3] = sql_trend;
                arr[4] = sql_item;
                arr[5] = sql_Patient_clob;
                
                try
                {
                    count = Dbcom.ExecuteBatch(arr);
                }
                catch (Exception)
                {

                    result = "F";
                }


            }
        }
        return count;
    }


    /// <summary>
    /// 获取文书的相信情况
    /// </summary>
    /// <param name="tid"></param>
    /// <param name="patient_id"></param>
    /// <param name="doctype"></param>
    /// <returns></returns>
    public InPatient_Doc GetDocbyId(string tid,string patient_id,string doctype)
    {
        try
        {          
            string sql = "select a.tid,a.pid,a.textkind_id,a.belongtosys_id,a.sickkind_id," +
                           " a.textname,a.doc_name,a.patient_Id,a.ishighersign,a.havehighersign," +
                           "a.havedoctorsign,a.submitted,a.createId,a.highersignuserid,a.israplacehightdoctor," +
                           "a.israplacehightdoctor2,a.SECTION_NAME  from t_patients_doc a ";
            if (doctype.Contains("Patient_Doc"))
            {
                sql = sql + " where a.tid='" + tid + "' and a.patient_id=" + patient_id + " order by a.doc_name";
            }
            else
            {
                sql = sql + " where a.textkind_id='" + tid + "' and a.patient_id=" + patient_id + "  order by a.doc_name";
            }

            DataSet ds = Dbcom.GetDataSet(sql);
            InPatient_Doc pDoc = new InPatient_Doc();
            DataRow row = ds.Tables[0].Rows[0];
            pDoc.Id = Convert.ToInt32(row["tid"]);
            pDoc.Patient_id = row["patient_Id"].ToString();
            pDoc.Pid = row["pid"].ToString();

            if (row["textkind_id"].ToString() != "")
                pDoc.Textkind_id = Convert.ToInt32(row["textkind_id"]);

            if (row["belongtosys_id"].ToString() != "")
                pDoc.Belongtosys_id = Convert.ToInt32(row["belongtosys_id"]);
            //pDoc.Patients_doc =row["patients_doc"].ToString();
            if (row["sickkind_id"].ToString() != "")
                pDoc.Sickkind_id = Convert.ToInt32(row["sickkind_id"]);

            pDoc.Docname = row["doc_name"].ToString().TrimStart();
            pDoc.Textname = row["textname"].ToString().TrimStart();
            pDoc.Ishighersign = row["ishighersign"].ToString();
            pDoc.Havehighersign = row["havehighersign"].ToString();
            pDoc.Havedoctorsign = row["Havedoctorsign"].ToString();
            pDoc.Submitted = row["submitted"].ToString();
            pDoc.Createid = row["createId"].ToString();
            pDoc.Highersignuserid = row["highersignuserid"].ToString();
            pDoc.Isreplacehighdoctor = row["israplacehightdoctor"].ToString();
            pDoc.Isreplacehighdoctor2 = row["israplacehightdoctor2"].ToString();
            pDoc.Section_name = row["SECTION_NAME"].ToString();
            return pDoc;
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 判断该类单例文书是否已经存在
    /// </summary>
    /// <param name="id"></param>
    /// /// <param name="patient_id">病人id</param>
    /// <returns></returns>
    public string isExitRecord(int id, int patient_id)
    {       
        string sql = "select tid num from t_patients_doc where textkind_id =" + id + " and patient_id='" + patient_id + "' ";        
        string tid = Dbcom.ReadSqlVal(sql, 0, "num");
        return tid;
    }

    /// <summary>
    /// 根据文书的ID 获取文书的XMl
    /// </summary>
    /// <param name="tid"></param>
    /// <returns></returns>
    
    public string GetTextDocXmlById(string tid)
    {      
        string content = "";
        content = Dbcom.ReadSqlVal("select * from T_PATIENT_DOC_COLB where tid=" + tid + "", 0, "CONTENT");
        //if (content == "" || content == null)
        //{
        //    content = App.DownLoadFtpPatientDoc(dt.Rows[0]["tid"].ToString() + ".xml", inpatient.Id.ToString()); //dt.Rows[0]["patients_doc"].ToString();
        //}
        return content;
    }



    public void SaveDoc(ref int Tid, int TextKind_id,bool blfalse,bool IsMore, string textTitle,string Role_type,string User_id, InPatientInfo InpatientInfo, 
                          string haveSuperior,string havaTube, string Belong_ToSys_ID, string SickKind_ID, string OldTextName, 
                          string TextSuperiorSignature, string SuporSign,bool haveD, bool isTakeSuperiorZz,bool isTakeSuperiorZr,
                          string qualityTitle, string tempxmldocstr)
    {       
        if (Tid != 0)
        {
            ////修改文书内容
            //if (blfalse) //点的提交按钮
            //{
            //    DataTable dt = Dbcom.GetDataSet(string.Format("select submitted from T_PATIENTS_DOC where TID = {0} AND PATIENT_ID = '{1}'", CurrentFrmText.MyDoc.Us.Tid, CurrentFrmText.MyDoc.Us.InpatientInfo.Id)).Tables[0];
            //    if (dt != null && dt.Rows.Count > 0)
            //    {
            //        string submmit = dt.Rows[0][0].ToString();
            //        if (submmit == "Y")
            //        {
            //           // LogHelper.SystemLog("修改", CurrentFrmText.MyDoc.Us.Tid.ToString(), CurrentFrmText.MyDoc.Us.InpatientInfo.PId.ToString(), CurrentFrmText.MyDoc.Us.InpatientInfo.Id);
            //        }
            //        else
            //        {
            //            //LogHelper.SystemLog("创建", CurrentFrmText.MyDoc.Us.Tid.ToString(), CurrentFrmText.MyDoc.Us.InpatientInfo.PId.ToString(), CurrentFrmText.MyDoc.Us.InpatientInfo.Id);
            //            //if (TextKind_id == 890)
            //            //{
            //            //    CurrentFrmText.MyDoc.InsertJobTemp(qualityTitle);
            //            //}
            //        }
            //    }
            //}

            string sql_tks = "SELECT ISRAPLACEHIGHTDOCTOR,ISRAPLACEHIGHTDOCTOR2 FROM T_Patients_Doc T WHERE T.TID = '" + Tid + "'";
            DataTable dt = Dbcom.GetDataSet(sql_tks).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                isTakeSuperiorZz = dt.Rows[0]["ISRAPLACEHIGHTDOCTOR"].ToString() == "Y";
                isTakeSuperiorZr = dt.Rows[0]["ISRAPLACEHIGHTDOCTOR2"].ToString() == "Y";
            }
            
            if (Role_type == "N")
            {
                //当护士操作的时候，特殊处理
                haveSuperior = "Y";
            }

             string sql = string.Format("update T_PATIENTS_DOC set HAVEDOCTORSIGN = '{3}' ,ISHIGHERSIGN = '{4}',HAVEHIGHERSIGN = '{5}',submitted='{6}',highersignuserid = '{7}' {2} where TID = {0} AND PATIENT_ID = '{1}' ",
                Tid,
                InpatientInfo.Id,
                textTitle == "" ? "" : ",doc_name ='" + textTitle.Trim() + "'",
                havaTube,
                TextSuperiorSignature,
                haveSuperior,
                (blfalse == true ? "Y" : "N"),  //暂存/提交,
                SuporSign);
            if (Dbcom.ExecuteSQL(sql) > 0)
            {
                //CurrentFrmText.MyDoc.ExcuteDiagnoseSql();
                
                #region 质控表
                if (blfalse)
                {
                    if (Dbcom.GetDataSet("SELECT pid from t_quality_text where tid = '" + Tid + "'").Tables[0].Rows.Count < 1)
                    {
                        //如果质控表没数据 插入该数据
                        string sql2 = string.Format(" insert into t_quality_text"
                                                  + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
                                                  + " values"
                                                  + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')"
                                                  , ""
                                                  , TextKind_id
                                                  , InpatientInfo.PId
                                                  , Dbcom.GetSystemTime().ToString("yyyy-MM-dd HH:mm")
                                                  , Tid, InpatientInfo.Id);
                        Dbcom.ExecuteSQL(sql2);
                    }
                    string sql3 = string.Format("UPDATE t_quality_text SET textname ='{0}' where tid = {1}"
                        , qualityTitle
                        , Tid);
                    int i = Dbcom.ExecuteSQL(sql3);
                    if (haveD && Dbcom.GetDataSet("SELECT PATIENT_ID from t_job_temp where operate_type='D型病历' and PATIENT_ID = '" + InpatientInfo.Id + "'").Tables[0].Rows.Count < 1)
                    {
                        string strAge = string.Empty;
                        if (Dbcom.IsNumeric(InpatientInfo.Age))
                        {
                            strAge = InpatientInfo.Age;
                        }
                        string sqlD = string.Format("insert into t_job_temp(pid,operate_type,operate_time,patient_id,age) " +
                                               " values('{0}','{1}',to_TIMESTAMP('{2}','yyyy-MM-dd hh24:mi'),'{3}','{4}')",
                                                InpatientInfo.PId, "D型病历",
                                                InpatientInfo.In_Time.ToString("yyyy-MM-dd HH:mm"),
                                                InpatientInfo.Id, strAge);
                        Dbcom.ExecuteSQL(sqlD);                                                                           
                    }

                }
                #endregion
                if (blfalse)
                {//提交
                 //App.SetToolButtonByUser("ttsbtnPrint", true);//打印
                 //App.SetToolButtonByUser("ttsbtnPrintContinue", true);//续打
                }

                String sql_clob = string.Format("update T_PATIENT_DOC_COLB set CONTENT=:doc1 where TID = '{0}'", Tid);
                DBParameter[] xmlPars = new DBParameter[1];
                xmlPars[0] = new DBParameter();
                xmlPars[0].ParameterName = "doc1";
                xmlPars[0].Value = tempxmldocstr;
                xmlPars[0].DBType = Oracle.ManagedDataAccess.Client.OracleDbType.Clob;
                Dbcom.ExecuteSQLWithParams(sql_clob, xmlPars);             
                //CurrentFrmText.MyDoc.Modified = false;
            }
            else
            {

                //App.SetToolButtonByUser("ttsbtnPrint", false);//打印
                //App.SetToolButtonByUser("ttsbtnPrintContinue", false);//续打
                //App.Msg("文书保存失败！");
                return;
            }
            //this.Modified 
        }
        else
        {
            //文书Tid
            if (!IsMore)
            {
                DataTable havaCount =
                    Dbcom.GetDataSet(string.Format("SELECT COUNT(t.pid) FROM T_PATIENTS_DOC T WHERE T.PATIENT_ID = '{0}' AND t.textkind_id = '{1}'", InpatientInfo.Id, TextKind_id)).Tables[0];
                if (havaCount != null && Convert.ToInt32(havaCount.Rows[0][0]) > 0)
                {                   
                    return;
                }
            }
            int tid = Dbcom.GenId();
            string strinsert =
                string.Format("insert into T_Patients_Doc(tid,CREATEID, pid, textkind_id, belongtosys_id, sickkind_id, textname,submitted,PATIENT_ID,DOC_NAME,HAVEDOCTORSIGN,ISHIGHERSIGN,HAVEHIGHERSIGN,highersignuserid,ISRAPLACEHIGHTDOCTOR,ISRAPLACEHIGHTDOCTOR2,SECTION_NAME,BED_NO,SICK_AREA_NAME) " +
                              "values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}')"
                              , tid.ToString()                                                 //文书ID
                              , User_id //是否提交按钮
                              , InpatientInfo.PId
                              , TextKind_id
                              , Belong_ToSys_ID
                              , SickKind_ID
                              , OldTextName
                              , (blfalse == true ? "Y" : "N")  //暂存/提交
                              , InpatientInfo.Id
                              , textTitle.Trim()
                              , havaTube
                              , TextSuperiorSignature
                              , haveSuperior
                              , SuporSign
                              , (isTakeSuperiorZz == true ? "Y" : "N")
                              , (isTakeSuperiorZr == true ? "Y" : "N")
                              , InpatientInfo.Section_Name
                              , InpatientInfo.Sick_Bed_Name
                              , InpatientInfo.Sick_Area_Name);
            //如果保存文书成功
            if (Dbcom.ExecuteSQL(strinsert) > 0)
            {
                //CurrentFrmText.MyDoc.Us.Tid = tid;
                //CurrentFrmText.MyDoc.ExcuteDiagnoseSql();


               // App.UpLoadFtpPatientDoc(tempxmldoc.OuterXml, CurrentFrmText.MyDoc.Us.Tid.ToString() + ".xml", CurrentFrmText.MyDoc.Us.InpatientInfo.Id.ToString());
                if (blfalse)
                {
                    //LogHelper.SystemLog("创建", CurrentFrmText.MyDoc.Us.Tid.ToString(), CurrentFrmText.MyDoc.Us.InpatientInfo.PId.ToString(), CurrentFrmText.MyDoc.Us.InpatientInfo.Id);
                    //if (CurrentFrmText.MyDoc.Us.TextKind_id == 890)
                    //{
                    //    CurrentFrmText.MyDoc.InsertJobTemp(qualityTitle);
                    //}
                    /***
                     * 质控表
                     * 
                     */
                    string sql2 = string.Format(" insert into t_quality_text"
                                              + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
                                              + " values"
                                              + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')",
                                              qualityTitle
                                              , TextKind_id
                                              , InpatientInfo.PId
                                              , Dbcom.GetSystemTime().ToString("yyyy-MM-dd HH:mm")
                                              , tid
                                              , InpatientInfo.Id);
                    if (Dbcom.ExecuteSQL(sql2) < 1)
                    {
                        //App.Msg("质控表保存失败" + sql2);
                    }
                    // 首次病程中如果在病历分型中有“D型病历”，则在提交文书的同时需要插入一下事件：
                    // insert into v_job_temp(pid,operate_type,operate_time,patient_id,age)
                    //values('病人pid','D型病历','入院时间','病人id','年龄')

                    if (haveD && Dbcom.GetDataSet("SELECT PATIENT_ID from t_job_temp where operate_type='D型病历' and PATIENT_ID = '" + InpatientInfo.Id + "'").Tables[0].Rows.Count < 1)
                    {
                        string strAge = string.Empty;
                        if (Dbcom.IsNumeric(InpatientInfo.Age))
                        {
                            strAge = InpatientInfo.Age;
                        }
                        string sqlD = string.Format("insert into t_job_temp(pid,operate_type,operate_time,patient_id,age) " +
                                               " values('{0}','{1}',to_TIMESTAMP('{2}','yyyy-MM-dd hh24:mi'),'{3}','{4}')",
                                                InpatientInfo.PId, "D型病历",
                                                InpatientInfo.In_Time.ToString("yyyy-MM-dd HH:mm"),
                                                InpatientInfo.Id, strAge);
                        if (Dbcom.ExecuteSQL(sqlD) < 1)
                        {
                            //App.Msg("质控事件表保存失败");
                        }
                    }


                }
                if (blfalse)
                {//提交
                    //App.SetToolButtonByUser("ttsbtnPrint", true);//打印
                    //App.SetToolButtonByUser("ttsbtnPrintContinue", true);//续打
                }
                string sql_clob = "insert into T_PATIENT_DOC_COLB(tid,CONTENT)values(" + tid + ",:doc1)";
                DBParameter[] xmlPars = new DBParameter[1];
                xmlPars[0] = new DBParameter();
                xmlPars[0].ParameterName = "doc1";
                xmlPars[0].Value = tempxmldocstr;
                xmlPars[0].DBType = Oracle.ManagedDataAccess.Client.OracleDbType.Clob;
                Dbcom.ExecuteSQLWithParams(sql_clob, xmlPars);

                Tid = tid;
                //App.Msg("文书保存成功！");
                //CurrentFrmText.MyDoc.Modified = false;
            }
            else
            {
                //App.SetToolButtonByUser("ttsbtnPrint", false);//打印
                //App.SetToolButtonByUser("ttsbtnPrintContinue", false);//续打
                //App.Msg("文书保存失败!");

            }
        }
    }

    #region 文书相关操作私有方法

    private void setXmlFont(XmlNodeList list, XmlElement bodyElement)
    {
        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].Name == "div")
            {
                bool eflag = false;
                for (int j = 0; j < list[i].Attributes.Count; j++)
                {
                    //fontsize
                    if (list[i].Attributes[j].Name == "fontsize")
                    {
                        eflag = true;
                    }
                }
                //袁杨修改  150818
                //if (!eflag)
                //{

                //    XmlAttribute xmlAttribute = bodyElement.OwnerDocument.CreateAttribute("fontsize");
                //    xmlAttribute.Value = "14";
                //    list[i].Attributes.Append(xmlAttribute);
                //}                   

            }

            if (list[i].ChildNodes.Count > 0)
            {
                setXmlFont(list[i].ChildNodes, bodyElement);
            }
        }

    }


    /// <summary>
    /// 获得当前节点病人文书
    /// </summary>
    /// <param name="nodes">当前节点下的文书内容</param>
    /// <returns>返回Patient_Doc</returns>
    private InPatient_Doc[] GetSelectNodes(string patient_id, string textid, string DocType)
    {
        //InPatientInfo inpatient = GetInpatientByBedId(trvInpatientManager.Nodes, dtlBedNumber.SelectedValue.ToString());
        //string sql = "select a.tid,a.patients_doc,a.textname,a.textkind_id from t_patients_doc a" +
        //             " left join t_quality_text b on a.tid=b.tid where a.patient_id='" + this.currentPatient.Id + "' "+
        //             " and a.tid=" + text.Id + " order by a.tid";      
        string sql = "";
        if (!DocType.Contains("Class_Text"))
        {
            sql = "select a.tid,a.textname,a.textkind_id,a.createid,a.submitted,a.doc_name,a.section_name,b.ISNEWPAGE,Bed_no from t_patients_doc a inner join t_text b on a.textkind_id = b.id " +
                       "where a.patient_id='" + patient_id + "' and a.tid=" + textid + " order by doc_name";
        }
        else
        {
            sql = "select a.tid,a.textname,a.textkind_id,a.createid,a.submitted,a.doc_name,c.issimpleinstance,a.section_name,c.ISNEWPAGE,Bed_no from t_patients_doc a" +
                                      " inner join t_text c on a.textkind_id = c.id" +
                                      " where patient_id='" + patient_id + "'  and  textkind_id!=134" +    //textkind_id=134术前讨论
                                      " and textkind_id=" + textid + "  and submitted='Y' order by doc_name";
        }
        DataSet ds = Dbcom.GetDataSet(sql);
        InPatient_Doc[] patient_Docs = null;
        //string[,] arrs = null;
        if (ds != null)
        {
            DataTable dt = ds.Tables[0];
            if (dt != null)
            {
                //去掉相同的文书
                int tid = 0;
                //arrs = new string[dt.Rows.Count,2];
                patient_Docs = new InPatient_Doc[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //arrs[i,0] = dt.Rows[i]["patients_doc"].ToString();
                    //arrs[i, 1] = dt.Rows[i]["tid"].ToString();
                    if (tid != Convert.ToInt32(dt.Rows[i]["tid"].ToString()))
                    {
                        patient_Docs[i] = new InPatient_Doc();
                        patient_Docs[i].Patients_doc = Dbcom.ReadSqlVal("select * from T_PATIENT_DOC_COLB where tid=" + dt.Rows[i]["tid"].ToString() + "", 0, "CONTENT");
                        patient_Docs[i].Id = Convert.ToInt32(dt.Rows[i]["tid"].ToString());
                        patient_Docs[i].Textkind_id = Convert.ToInt32(dt.Rows[i]["textkind_id"].ToString());
                        patient_Docs[i].Createid = dt.Rows[i]["createid"].ToString();
                        patient_Docs[i].Submitted = dt.Rows[i]["submitted"].ToString();
                        patient_Docs[i].Docname = dt.Rows[i]["doc_name"].ToString();
                        patient_Docs[i].Section_name = dt.Rows[i]["section_name"].ToString();
                        patient_Docs[i].Bed = dt.Rows[i]["Bed_no"].ToString();
                        tid = Convert.ToInt32(dt.Rows[i]["tid"].ToString());

                        if (dt.Rows[i]["ISNEWPAGE"].ToString() == "Y")
                        {
                            patient_Docs[i].Isnewpage = "Y";
                        }
                        else
                        {
                            patient_Docs[i].Isnewpage = "N";
                        }
                    }
                }
            }
        }
        return patient_Docs;

    }

    /// <summary>
    /// 把文书内容节点插入到具体的文书下
    /// </summary>
    /// <param name="nodes">文书类别</param>
    /// <param name="node">文书内容</param>
    private void GetPatientDoc(UcTreeNode[] nodes, UcTreeNode node)
    {
        InPatient_Doc doc = node.Tag as InPatient_Doc;
        if (doc != null)
        {
            //代主治查房显示*号
            if (doc.Textkind_id == 126 && doc.Isreplacehighdoctor == "Y")
            {
                node.Text = "*" + doc.Docname;
            }
            //代主任查房显示△
            if (doc.Textkind_id == 126 && doc.Isreplacehighdoctor2 == "Y")
            {
                node.Text = "△" + doc.Docname;
            }
        }

        foreach (UcTreeNode TempNode in nodes)
        {
            Class_Text text = TempNode.Tag as Class_Text;
            if (text != null)
            {
                if (text.Issimpleinstance == "1")   //多例文书
                {
                    if (doc.Textkind_id == text.Id) //如果当前文书和树节点的文书id相同，就把该文书添加树节点的下面
                    {
                        if (doc.Submitted == "N")//暂存显示为蓝色
                        {
                            node.ForeColor = ColorTranslator.ToHtml(Color.Blue);
                            node.Text += "(暂存)";
                        }
                        else if (doc.Havedoctorsign == "N" && doc.Havehighersign == "N")//N表示经治医师未签字的文书，显示为红色
                        {
                            node.ForeColor = ColorTranslator.ToHtml(Color.Red);
                            node.Text += "(缺经治医师签名)";
                        }
                        else if (doc.Ishighersign == "Y")//是否需要上级医师签字，Y表示需要
                        {
                            if (doc.Havehighersign == "N")//上级医师是否已签字，N代表没签
                            {
                                node.ForeColor = ColorTranslator.ToHtml(Color.Orange);
                                node.Text += "(缺上级医师签名)";
                            }
                        }
                        TempNode.Childnodes.Add((UcTreeNode)node);
                        break;
                    }
                }
                else
                {
                    if (TempNode.Childnodes.Count == 0)
                    {
                        if (doc.Textkind_id == text.Id)   //如果当前文书和树节点的文书id相同,说明该单实例文书已经有内容了，颜色则变为蓝色
                        {
                            //TempNode.SelectedImageIndex = 16;
                            TempNode.Imageindex = 16;
                            if (doc.Submitted == "N")//暂存显示为蓝色
                            {
                                TempNode.ForeColor = ColorTranslator.ToHtml(Color.Blue);
                                TempNode.Text += "(暂存)";
                            }
                            else if (doc.Havedoctorsign == "N" && doc.Havehighersign == "N")//N表示经治医师未签字的文书，显示为红色
                            {
                                TempNode.ForeColor = ColorTranslator.ToHtml(Color.Red);
                                TempNode.Text += "(缺经治医师签名)";
                            }
                            else if (doc.Ishighersign == "Y")//是否需要上级医师签字，Y表示需要
                            {
                                if (doc.Havehighersign == "N")//上级医师是否已签字，N代表没签
                                {
                                    TempNode.ForeColor = ColorTranslator.ToHtml(Color.Orange);
                                    TempNode.Text += "(缺上级医师签名)";
                                }
                            }
                            break;
                        }
                    }
                }
            }
            if (TempNode.Childnodes.Count > 0)
            {
                GetPatientDoc(TempNode.Childnodes.ToArray(), node);
            }
        }
    }

    /// <summary>
    /// 获取医生类缩写的文书
    /// </summary>
    /// <param name="trvD"></param>
    private void getDoctorFinishedText(ref UcTreeNode trvD, string docStrs)
    {       
        TextOperation textset = new TextOperation(cm);       
        string sql = "select * from T_TEXT where enable_flag='Y' and right_range in('A','D') order by shownum asc ";

        if (trvD.Childnodes == null)
        {
            trvD.Childnodes = new List<UcTreeNode>();
        }
        //118
        // string sql = "select * from T_TEXT where enable_flag='Y' and id in(" + docStrs + ",118,103" + ") and right_range='D' order by shownum asc "; //and right_range='D' and id in(" + docStrs + ") or id in (118,2022)

        DataSet dstree = Dbcom.GetDataSet(sql);
        Class_Text[] Directionarys = textset.GetSelectClassDs(dstree);
        if (Directionarys != null)
        {
            /*
             * 首页
             */
            for (int i = 0; i < Directionarys.Length; i++)
            {
                UcTreeNode tn = new UcTreeNode();
                tn.Tag = Directionarys[i];
                tn.Text = Directionarys[i].Textname;
                tn.Name = Directionarys[i].Id.ToString();
                if (Directionarys[i].Issimpleinstance == "1")
                {
                    tn.Imageindex = 22; //多例
                }
                else
                {
                    tn.Imageindex = 21; //单例
                }

                //if (tn.Name == "118" ||
                //    tn.Name == "2022")
                //袁杨修改 150819 增加中医病案首页
                if (tn.Name == "118" ||
                   tn.Name == "2022")
                {
                    trvD.Childnodes.Add(tn);
                }
            }

            /*
            * 入院记录
            */
            for (int i = 0; i < Directionarys.Length; i++)
            {
                if (Directionarys[i].Parentid == 102 || Directionarys[i].Id == 119)
                {
                    UcTreeNode tn = new UcTreeNode();
                    tn.Tag = Directionarys[i];
                    tn.Text = Directionarys[i].Textname;
                    tn.Name = Directionarys[i].Id.ToString();
                    if (Directionarys[i].Issimpleinstance == "1")
                    {
                        tn.Imageindex = 22;
                    }
                    else
                    {
                        tn.Imageindex = 21;
                    }

                    trvD.Childnodes.Add(tn);
                }
            }

            /*
             * 病程记录
             * 103
             */

            for (int i = 0; i < Directionarys.Length; i++)
            {
                if (Directionarys[i].Id == 103)
                {
                    UcTreeNode tn = new UcTreeNode();
                    tn.Tag = Directionarys[i];
                    tn.Text = Directionarys[i].Textname;
                    tn.Name = Directionarys[i].Id.ToString();
                    if (Directionarys[i].Issimpleinstance == "1")
                    {
                        tn.Imageindex = 22;
                    }
                    else
                    {
                        tn.Imageindex = 21;
                    }

                    for (int j = 0; j < Directionarys.Length; j++)
                    {
                        if (Directionarys[j].Parentid == 103)
                        {
                            UcTreeNode tn2 = new UcTreeNode();
                            tn2.Tag = Directionarys[j];
                            tn2.Text = Directionarys[j].Textname;
                            tn2.Name = Directionarys[j].Id.ToString();
                            if (Directionarys[i].Issimpleinstance == "1")
                            {
                                tn.Imageindex = 22;
                            }
                            else
                            {
                                tn.Imageindex = 21;
                            }
                            tn.Childnodes.Add(tn2);
                        }
                    }
                    trvD.Childnodes.Add(tn);
                    break;
                }
            }

            /*
             * 其他文书（不含知情同意书）
             */
            for (int i = 0; i < Directionarys.Length; i++)
            {
                if (Directionarys[i].Parentid != 103 && Directionarys[i].Parentid != 102 && Directionarys[i].Id != 119 &&
                    Directionarys[i].Id != 118 && Directionarys[i].Txxttype != "19760")
                {
                    UcTreeNode tn = new UcTreeNode();
                    tn.Tag = Directionarys[i];
                    tn.Text = Directionarys[i].Textname;
                    tn.Name = Directionarys[i].Id.ToString();
                    if (Directionarys[i].Issimpleinstance == "1")
                    {
                        tn.Imageindex = 22;
                    }
                    else
                    {
                        tn.Imageindex = 21;
                    }

                    trvD.Childnodes.Add(tn);
                }
            }

            /*
            * 知情同意书
            */
            for (int i = 0; i < Directionarys.Length; i++)
            {
                if (Directionarys[i].Parentid != 103 && Directionarys[i].Parentid != 102 &&
                    Directionarys[i].Id != 118 && Directionarys[i].Txxttype == "19760")
                {

                    UcTreeNode tn = new UcTreeNode();
                    tn.Tag = Directionarys[i];
                    tn.Text = Directionarys[i].Textname;
                    tn.Name = Directionarys[i].Id.ToString();
                    if (Directionarys[i].Issimpleinstance == "1")
                    {
                        tn.Imageindex = 22;
                    }
                    else
                    {
                        tn.Imageindex = 21;
                    }

                    trvD.Childnodes.Add(tn);


                }
            }
            //SetTreeNodesImage(trvD.Nodes);
        }
    }


    /// <summary>
    /// 当前病人当前文书是否存在对应要读取内容的文书
    /// </summary>
    /// <param name="text_id"></param>
    /// <returns></returns>
    private bool Text_id_haveDoc(string text_id,string patient_id)
    {       
        bool flag = false;
        try
        {
            string textlist = "47560141,119,47553087,47553088,47553089,47561196,102,120,121";
            string sql = "select * from t_patients_doc where patient_id=" + patient_id + "";
            if (text_id == "125")
            {
                sql += "  and textkind_id in (" + textlist + ")";
            }
            else if (textlist.Contains(text_id))
            {
                sql += "  and textkind_id=125 ";
            }
            else
            {
                return flag;
            }
            DataSet ds = Dbcom.GetDataSet(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                flag = true;
            }

        }
        catch
        {
            flag = false;
        }
        return flag;
    }

    /// <summary>
    /// 是否是要复制的内容
    /// </summary>
    /// <param name="sc"></param>
    /// <returns></returns>
    private bool isCloneContent(string sc, string text_id)
    {
        bool flag = false;
        string[] source_s = "主诉,现病史".Split(',');
        sc = sc.Replace(":", " ").Replace("：", " ").Trim();
        for (int i = 0; i < source_s.Length; i++)
        {
            if (!string.IsNullOrEmpty(sc) && sc == source_s[i])
            {
                return true;
            }
        }
        if (text_id == "125")
        {
            if (sc == "辅助检查")
                flag = true;
        }
        string textlist = "47560141,119,47553087,47553088,47553089,47561196,102,120,121";
        if (textlist.Contains(text_id))
        {
            //门诊及院外重要检查结果(辅助检查）：
            if (sc.Contains("门诊及院外重要检查结果") && sc.Contains("辅助检查"))
                flag = true;
        }
        return flag;
    }


    /// <summary>
    /// 住院志同步到首程
    /// </summary>
    /// <param name="xml"></param>
    /// <param name="sc"></param>
    /// <returns></returns>
    private string xmlContent(XmlDocument xml, string sc)
    {
        try
        {
            string content = "";
            sc = sc.Replace(":", " ").Replace("：", " ").Trim();
            XmlNode bodynode = xml.ChildNodes[0].SelectSingleNode("body");
            XmlNodeList list = ((XmlElement)bodynode).GetElementsByTagName("div");//input
            foreach (XmlNode xn in list)
            {
                if (xn.Attributes["title"] != null)
                {
                    string xnname = xn.Attributes["title"].Value.ToString().Trim();
                    xnname = xnname.Replace(":", " ").Replace("：", " ").Trim();
                    if (sc != "辅助检查")
                    {
                        if (!string.IsNullOrEmpty(sc) && sc == xnname)
                        {
                            if (!String.IsNullOrEmpty(xn.InnerText))
                            {
                                content = xn.InnerXml;// xmlFilter(xn);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (xnname.Contains("门诊及院外重要检查结果"))
                        {
                            if (!String.IsNullOrEmpty(xn.InnerText))
                            {
                                content = xn.InnerXml;// xmlFilter(xn);
                                break;
                            }
                        }
                    }
                }
            }
            return content;
        }
        catch
        {
            return "";
        }
    }


    /// <summary>
    /// 首程同步到住院志
    /// </summary>
    /// <param name="xml"></param>
    /// <param name="sc"></param>
    /// <returns></returns>
    private string docContent(XmlDocument xml, string sc)
    {
        try
        {
            string content = "";
            sc = sc.Replace(":", " ").Replace("：", " ").Trim();
            XmlNode bodynode = xml.ChildNodes[0].SelectSingleNode("body");
            XmlNodeList list = ((XmlElement)bodynode).GetElementsByTagName("div");//input
            foreach (XmlNode xn in list)
            {
                if (xn.Attributes["title"] != null)
                {
                    string xnname = xn.Attributes["title"].Value.ToString().Trim();
                    xnname = xnname.Replace(":", " ").Replace("：", " ").Trim();

                    if (sc.Contains("辅助检查") && sc.Contains("门诊及院外重要检查结果"))
                    {
                        if (xnname.Contains("辅助检查"))
                        {
                            if (!String.IsNullOrEmpty(xn.InnerText))
                            {
                                content = xn.InnerXml;// xmlFilter(xn);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(sc) && sc == xnname)
                        {
                            if (!String.IsNullOrEmpty(xn.InnerText))
                            {
                                content = xn.InnerXml;// xmlFilter(xn);
                                break;
                            }
                        }
                    }
                }
            }
            return content;
        }
        catch
        {
            return "";
        }
    }


    /// <summary>
    /// 当前病人对应文书文书TID
    /// </summary>
    /// <param name="text_id"></param>
    /// <returns></returns>
    private string getTidByTextid(string text_id,string patient_id)
    {
        try
        {          
            string textlist = "47560141,119,47553087,47553088,47553089,47561196,102,120,121";
            string sql = "select * from t_patients_doc where patient_id=" + patient_id + "";
            if (text_id == "125")
            {
                sql += "  and textkind_id in (" + textlist + ")";
            }
            else
            {
                sql += "  and textkind_id=125 ";
            }
            return Dbcom.ReadSqlVal(sql, 0, "tid");
        }
        catch
        { return ""; }
    }


    /// <summary>
    /// 根据文书节点属性判断是否可以删除文书
    /// </summary>
    /// <param name="doc"></param>
    /// <returns></returns>
    private bool ISDelByXmlNode(int id,string patient_id,string User_name)
    {       
        //string sql = "select patients_doc from t_patients_doc where tid=" + id;
        string content = "";
        content = content = Dbcom.ReadSqlVal("select * from T_PATIENT_DOC_COLB where tid=" + id + "", 0, "CONTENT");
        //if (content == null || content == "")
        //{
        //    content = Dbcom.DownLoadFtpPatientDoc(id + ".xml", currentPatient.Id.ToString());//App.ReadSqlVal(sql, 0, "patients_doc");
        //}
        if (content == null || content == "")
        {
            return true;
        }
        XmlDocument textDocument = new XmlDocument();
        textDocument.PreserveWhitespace = true;
        textDocument.LoadXml(content);

        XmlNodeList sign = textDocument.GetElementsByTagName("input");

        string sjysqm = "";//上级医师签名
        string gcysqm = "";//管床医生签名
        string ptysqm = "";//普通医生签名
                           /* 1.先判断上级医生是否签名，有的话当前操作人员是否是上级医生，不是的话直接返回“上级医师已签字，无法删除！”
                            * 2.上级医生没有签名，判断当前操作人员是否是上级医生，是的话可以操作
                            * 3.判断管床医生是否签名，有的话，当前认识是否是管床医生，是的话可以操作
                            * 4.没有管床医生，当前操作人员是否是管床医生，是的话能操作，不是的话返回不能
                            * 5.没有上级医生和管床医生，普通医生有的时候判断是否是当前是人是的话能操作不是的话不能操作，没有的话能操作
                            */
                           //找到上级医生签名，管床医师签名，普通医师签名
        foreach (XmlNode var in sign)
        {
            if (var.Attributes["name"] != null && var.Attributes["name"].Value == "上级医师签名")
            {
                foreach (XmlNode node in var.ChildNodes)
                {
                    //sjysqm += node.InnerText;
                    //袁杨添加 160408
                    string str_sql = "select t.user_name from t_userinfo t where t.user_id='" + var.Attributes["id"].Value.ToString() + "'";
                    DataSet ds_t = Dbcom.GetDataSet(str_sql);
                    if (ds_t.Tables[0].Rows.Count > 0)
                    {
                        sjysqm = ds_t.Tables[0].Rows[0]["user_name"].ToString(); ;
                    }
                }
            }
            if (var.Attributes["name"] != null && var.Attributes["name"].Value == "管床医师签名")
            {
                foreach (XmlNode node in var.ChildNodes)
                {
                    //gcysqm += node.InnerText;
                    //袁杨添加 160408
                    string str_sql = "select t.user_name from t_userinfo t where t.user_id='" + var.Attributes["id"].Value.ToString() + "'";
                    DataSet ds_t = Dbcom.GetDataSet(str_sql);
                    if (ds_t.Tables[0].Rows.Count > 0)
                    {
                        gcysqm = ds_t.Tables[0].Rows[0]["user_name"].ToString(); ;
                    }
                }
            }
            if (var.Attributes["name"] != null && var.Attributes["name"].Value == "普通医师签名")
            {
                foreach (XmlNode node in var.ChildNodes)
                {
                    // ptysqm += node.InnerText;
                    //袁杨添加 160408
                    string str_sql = "select t.user_name from t_userinfo t where t.user_id='" + var.Attributes["id"].Value.ToString() + "'";
                    DataSet ds_t = Dbcom.GetDataSet(str_sql);
                    if (ds_t.Tables[0].Rows.Count > 0)
                    {
                        ptysqm = ds_t.Tables[0].Rows[0]["user_name"].ToString(); ;
                    }
                }
            }
        }
        string gcysmz = "";
        string ishighersign = "";
        string havehighersign = "";
        string havedoctorsign = "";
        string SqlHavingHigh = "select ishighersign,havehighersign,havedoctorsign,b.sick_doctor_name  from t_patients_doc a inner join t_in_patient b on a.patient_id=b.id  where tid=" + id;
        DataSet ds = Dbcom.GetDataSet(SqlHavingHigh);
        if (ds != null)
        {
            DataTable dt = ds.Tables[0];
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    gcysmz = dt.Rows[0]["sick_doctor_name"].ToString();
                    ishighersign = dt.Rows[0]["ishighersign"].ToString();//是否需要上级医生签名
                    havehighersign = dt.Rows[0]["havehighersign"].ToString();//是否有上级医生签名
                    havedoctorsign = dt.Rows[0]["havedoctorsign"].ToString();//是否有管床医生签名
                }
            }
        }
        string[] ptysnumber = ptysqm.Trim().Split(' ');
        #region
        if (ptysnumber.Length >= 1)
        {
            ArrayList temp = new ArrayList();
            for (int i = 0; i < ptysqm.Length; i++)
            {
                //temp[i] = st[i];
                if (temp.Count == 0)
                    temp.Add(ptysqm[i]);
                else
                {
                    if (temp[temp.Count - 1].ToString() != " ")
                    {
                        temp.Add(ptysqm[i]);
                    }
                    else
                    {

                        if (ptysqm[i].ToString() != " ")
                            temp.Add(ptysqm[i]);
                    }
                }
            }
            ptysqm = "";
            for (int i = 0; i < temp.Count; i++)
            {
                ptysqm += temp[i];
            }
            ptysnumber = ptysqm.Trim().Split(' ');
        }
        if (ptysnumber.Length == 1)
        {
            if (havedoctorsign == "Y" && gcysqm == "" && gcysmz.Trim() == ptysqm.Trim())
            {
                gcysqm = ptysnumber[0].ToString();
                ptysqm = "";
            }
            else
            {
                ptysqm = ptysnumber[0].ToString();
            }

        }
        if (ptysnumber.Length == 2)
        {
            if (gcysmz == ptysnumber[1].ToString())
            {
                sjysqm = ptysnumber[0].ToString();
                gcysqm = ptysnumber[1].ToString();
                ptysqm = "";
            }
            else if (gcysmz == ptysnumber[0].ToString())
            {
                gcysqm = ptysnumber[0].ToString();
                ptysqm = ptysnumber[1].ToString();
            }
            else
            {
                sjysqm = ptysnumber[0].ToString();
                ptysqm = ptysnumber[1].ToString();
            }
        }
        if (ptysnumber.Length > 2)
        {
            sjysqm = ptysnumber[0].ToString();
            gcysqm = ptysnumber[ptysnumber.Length - 2].ToString();
            ptysqm = ptysnumber[ptysnumber.Length - 1].ToString();
        }
        #endregion
        if (sjysqm.Trim().Length > 0 && sjysqm.Contains("："))
        {
            sjysqm = sjysqm.Split('：')[1].Trim();
        }
        else
        {
            sjysqm = sjysqm.Trim();
        }

        if (gcysqm.Trim().Length > 0 && gcysqm.Contains("："))
        {
            gcysqm = gcysqm.Split('：')[1].Trim();
        }
        else
        {
            gcysqm = gcysqm.Trim();
        }
        //gcysqm = gcysqm.Trim();
        if (ptysqm.Trim().Length > 0 && ptysqm.Contains("："))
        {
            ptysqm = ptysqm.Split('：')[1].Trim();
        }
        else
        {
            ptysqm = ptysqm.Trim();
        }
        //ptysqm = ptysqm.Trim();

        if (sjysqm != "" && sjysqm != User_name)
        {           
            return false;

        }
        else
        {
            //判断管床医师是否签名
            if (gcysqm != "")
            {
                if (gcysqm == User_name)
                {
                    return true;
                }
                else
                {                   
                    return false;
                }
            }
            else
            {
                if (gcysmz == User_name)
                {
                    return true;
                }
                if (ptysqm.Length == 0)
                    return true;
                else if (ptysqm == User_name)
                    return true;
                else if (ptysqm != User_name)
                {                   
                    return false;
                }
            }
        }                   
        return false;
    }



    #endregion




}